package com.csw.flink.window

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.{SlidingProcessingTimeWindows, TumblingEventTimeWindows, TumblingProcessingTimeWindows}
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer

object Demo01TimeWindow {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //创建配置文件对象
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    /**
      * 创建kafka消费者
      */
    val consumer: FlinkKafkaConsumer[String] = new FlinkKafkaConsumer[String]("test_topicl", new SimpleStringSchema(), properties)

    //读取最新数据
    consumer.setStartFromLatest()

    val kafkaDS: DataStream[String] = env.addSource(consumer)

    val kvDS: KeyedStream[(String, Int), String] = kafkaDS.map((_, 1)).keyBy(_._1)

    /**
      * 时间窗口
      *
      * TumblingProcessingTimeWindows：滚动处理时间窗口
      * TumblingEventTimeWindows：滚动事件时间窗口
      *
      * SlidingProcessingTimeWindows：滑动处理时间窗口(每隔2秒处理5秒内的数据)
      * SlidingEventTimeWindows：滑动事件时间窗口
      */

    kvDS
      .window(SlidingProcessingTimeWindows.of(Time.seconds(5),Time.seconds(2)))
      .sum(1)
      .print()

    env.execute()
  }
}
